package org.jeecg.modules.unifysys.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.unifysys.entity.UnifyUserSystem;
import org.jeecg.modules.unifysys.mapper.UnifyUserSystemMapper;
import org.jeecg.modules.unifysys.service.IUnifyUserSystemService;
import org.jeecg.modules.unifysys.util.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.io.IOException;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @Description: 用户所在的系统
 * @Author: jeecg-boot
 * @Date:   2021-04-13
 * @Version: V1.0
 *
 * 系统编码；
 * 督查：sys_ducha
 * 重大：sys_zhongda
 * 招商：sys_zhaoshang
 * 经济 sys_jingji
 * 绩效 sys_jixiao
 */
@Service
public class UnifyUserSystemServiceImpl extends ServiceImpl<UnifyUserSystemMapper, UnifyUserSystem> implements IUnifyUserSystemService {


    @Autowired
    private ISysUserService userService;

    @Transactional
    @Override
    public int getOtherSysUserByPhone(String phone) {
        String postName="未设置";
        String orgCodeTxt="未设置";



        List<UnifyUserSystem> listsys =new ArrayList<>();

        /*
            重大系统查询用户
         */
        List<UnifyUserSystem> zhongdaList = getZhongDaSysUser(phone);
        listsys.addAll(zhongdaList);

        if(!ObjectUtils.isEmpty(zhongdaList)){
            UnifyUserSystem unifyUserSystem = zhongdaList.get(0);
            postName=unifyUserSystem.getPostName();
            orgCodeTxt=unifyUserSystem.getSysOrgCode();

        }

        /*
         *督查系统查询用户
         */
        List<UnifyUserSystem> duchaUser = getDuChaSystem(phone);
        listsys.addAll(duchaUser);

        if(listsys.size()==0){
            return 0;
        }
        SysUser user = new SysUser();
        UnifyUserSystem sysUser = listsys.get(0);
        String realName = sysUser.getRealName();
        user.setRealname(realName);
        user.setUsername(phone);
        user.setPhone(phone);
        user.setTelephone(phone);
        user.setPassword("zxy123456");
        user.setCreateTime(new Date());
        String salt = oConvertUtils.randomGen(8);
        user.setSalt(salt);
        String passwordEncode = PasswordUtil.encrypt(user.getUsername(), user.getPassword(), salt);
        user.setPassword(passwordEncode);
        user.setStatus(1);
        user.setDelFlag(CommonConstant.DEL_FLAG_0);
        userService.save(user);
        String id = user.getId();

        listsys.forEach(unifyUserSystem -> unifyUserSystem.setUserCode(id));
        this.saveBatch(listsys);

        return 1;
    }

    /**
     * 督查用户
     * @param phone
     * @return
     */
    @Override
    public List<UnifyUserSystem> getDuChaSystem(String phone) {

        String resu = HttpUtil.httpGet("http://120.78.158.120:8077/app/user/bytel", "telphone="+phone);
//        String resu = HttpUtil.httpGet("http://192.168.2.30:8080/app/user/bytel", "telphone="+phone);
        System.out.println(resu);
//        JsonObject jsonObject = new JsonObject();
        JSONObject jsonObject = JSON.parseObject(resu);
        String code = jsonObject.getString("code");
        List<UnifyUserSystem> userList  = new ArrayList<>();
        if("200".equals(code)){// 返回成功
            String data = jsonObject.getString("data");
            if(!ObjectUtils.isEmpty(data)){
                JSONArray array = JSONArray.parseArray(data);
                for (int i = 0; i < array.size(); i++) {
                    JSONObject obj = array.getJSONObject(i);
                    String realName = obj.getString("realName");
                    String mobile = obj.getString("mobile");
                    String userName = obj.getString("username");
                    String deptId = obj.getString("deptId");
                    String userId = obj.getString("userId");
                    String roleId = obj.getString("roleId");
                    Integer userType = obj.getInteger("userType");
                    String deptName = obj.getString("deptName");


                    UnifyUserSystem user = new UnifyUserSystem();
                    user.setRoleName("01".equals(roleId)?"县领导":"02".equals(roleId)?"主要领导":"03".equals(roleId)?"分管领导":"经办人" );
                    user.setRoleId(roleId);
                    user.setUsername(userName);
                    user.setRealName(realName);
                    user.setUserId(userId);
                    user.setUserSysName("督查系统");
                    user.setUserSysCode("sys_ducha");
                    user.setUserType(userType);
                    user.setDeptName(deptName);

                    userList.add(user);


                }
            }
        }
        return userList;
    }


    /**
     * 重大用户
     * @param phone
     * @return
     */
    @Override
    public List<UnifyUserSystem> getZhongDaSysUser(String phone)
    {                List<UnifyUserSystem> userList  = new ArrayList<>();
        String nameValuePairs="{ \"phone\":\""+phone+"\" }";
        try {
            JSONObject jsonObject = HttpUtil.sendPost("http://120.78.158.120:10086/sysApp/queryByPhone", nameValuePairs, "http");
            System.out.println(jsonObject);
            String code = jsonObject.getString("code");
            if("200".equals(code))
            {
                String result = jsonObject.getString("result");
                JSONObject  resultObj = JSONObject.parseObject(result);
                JSONArray userArray = resultObj.getJSONArray("records");

                for (int i = 0; i < userArray.size(); i++) {
                    JSONObject userObj = userArray.getJSONObject(i);
                    String realname = userObj.getString("realname");
                    String username = userObj.getString("username");
                    String id = userObj.getString("id");
                    String roleName = userObj.getString("roleName_dictText");
                    String telephone = userObj.getString("phone");
                    String role = userObj.getString("role");
                    String position = userObj.getString("position");
                    String deptId_dictText = userObj.getString("deptId_dictText");//临时字段；

                    UnifyUserSystem user = new UnifyUserSystem();
                    user.setPostName(position);
                    user.setUserId(id);
                    user.setUsername(username);
                    user.setRoleName(roleName);
                    user.setRealName(realname);
                    user.setRoleId(role);
                    user.setUserSysCode("sys_zhongda");
                    user.setUserSysName("重大系统");
                    user.setSysOrgCode(deptId_dictText);
                    userList.add(user);

                }
            return userList;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return userList;
    }


    @Transactional
    @Override
    public  void updateUnifySystemInfo(String userCode,String phone)
    {

        List<UnifyUserSystem> zhongDaSysUser = getZhongDaSysUser(phone);
        List<UnifyUserSystem> duChaSystem = getDuChaSystem(phone);
        List<UnifyUserSystem> uniList = new ArrayList<>();
        uniList.addAll(zhongDaSysUser);
        uniList.addAll(duChaSystem);

        uniList.forEach(system -> system.setUserCode(userCode));

        QueryWrapper<UnifyUserSystem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_code",userCode);
        boolean remove = this.remove(queryWrapper);

        this.saveBatch(uniList);

        if(!ObjectUtils.isEmpty(zhongDaSysUser))
        {
            UnifyUserSystem unifyUserSystem = zhongDaSysUser.get(0);

            SysUser user = userService.getById(userCode);
            user.setPostName(unifyUserSystem.getPostName());
            user.setOrgCodeTxt(unifyUserSystem.getSysOrgCode());
            userService.updateById(user);
        }



    }



}
